package com.wolfpire.workflow.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.wolfpire.system.common.EasyuiPage;
import com.wolfpire.system.common.Page;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.workflow.dao.FormsDao;
import com.wolfpire.workflow.om.Forms;


@Repository("formsDao")
public class FormsDaoImpl extends BaseHibernateDao<Forms, Long> implements FormsDao {

	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> queryFormsList(){
		String sql = "SELECT T.FORM_TYPE_ID as FORM_ID, T.FORM_NAME" +
				" FROM WF_FORMS T WHERE T.STATUS=1 ORDER BY T.FORM_TYPE_ID ASC";
		
		return getSession().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	}
	
	
	public Forms getFormsByFormTypeId(Long formTypeId){
		Criteria criteria = createCriteria( 
				Restrictions.eq("formTypeId", formTypeId) 
		);
		return (Forms) criteria.uniqueResult();
	}


	@Override
	public Page<Forms> findFormses(EasyuiPage<Forms> page, Forms filterForms) {
		Criterion[] criterions = createFilter(filterForms);
		int totalCount = this.findIntByCriteria(criterions);
		page.setTotalCount(totalCount);
		
		if (0 < totalCount) {
			Criteria c = createCriteria(criterions);
			c = this.setPageParameter(c, page);
			@SuppressWarnings({ "unchecked" })
			List<Forms> result = c.list();
			page.setDataList(result);
		}
		return page;
	}


	private Criterion[] createFilter(Forms filterForms) {
		if (null == filterForms) {
			return null;
		}
		List<Criterion> criterions = new ArrayList<Criterion>();
		if (null != filterForms.getFormTypeId()) {
			criterions.add(Restrictions.eq("formTypeId", filterForms.getFormTypeId()));
		}
		if (!StringUtils.isBlank(filterForms.getFormName())) {
			criterions.add(Restrictions.like("formName", filterForms.getFormName(), MatchMode.ANYWHERE));
		}
		if (!StringUtils.isBlank(filterForms.getFormCode())) {
			criterions.add(Restrictions.like("formCode", filterForms.getFormCode(), MatchMode.ANYWHERE));
		}
		if (!StringUtils.isBlank(filterForms.getStatus())) {
			criterions.add(Restrictions.eq("status", filterForms.getStatus()));
		}
		return criterions.toArray(new Criterion[criterions.size()]);
	}


	@SuppressWarnings("unchecked")
	@Override
	public List<Forms> list(Forms forms) {
		Criterion[] criterions = createFilter(forms);
		Criteria c = createCriteria(criterions);
		return c.list();
	}
}
